package api

import (
	"github.com/kataras/iris/v12"
	"github.com/mlogclub/simple/web"
	"github.com/mlogclub/simple/web/params"

	"bbs-go/internal/models"
	"bbs-go/internal/pkg/config"
	"bbs-go/internal/services"
)

type ResourcesController struct {
	Ctx iris.Context
}

func (c *ResourcesController) AnyList() *web.JsonResult {
	list, paging := services.ResourcesService.FindPageByParams(params.NewQueryParams(c.Ctx).EqByReq("types").LikeByReq("name").LikeByReq("description").PageByReq().Desc("id"))
	infos := []models.ResourcesInfo{}

	resourcesTypesList, err := services.ResourcesTypesService.FindSimpleAllList()
	if err != nil {
		return web.JsonError(err)
	}

	for _, item := range list {
		infos = append(infos, models.ResourcesInfo{
			Id:          item.Id,
			CreatedAt:   item.CreatedAt.Format("2006-01-02 15:04:05"),
			Name:        item.Name,
			Cover:       item.Cover,
			Description: item.Description,
			Types:       item.Types,
			TypesName:   filterResourceTypes(resourcesTypesList, item.Types),
			FileName:    item.FileName,
			FilePath:    config.Instance.Uploader.Local.Host + item.FilePath,
			Sort:        item.Sort,
			Status:      item.Status,
		})
	}
	return web.JsonData(&web.PageResult{Results: infos, Page: paging})
}

func filterResourceTypes(list []models.ResourcesTypes, typeId int) string {
	for _, item := range list {
		if item.Id == int64(typeId) {
			return item.Name
		}
	}
	return ""
}
